﻿using System;
using System.Text.RegularExpressions;
using mmCore.Common;

namespace mmUI.Managers
{
    public class UpdateManager
    {
        private static string _mLatestVersion = Config.AppVersion;
        public const string WebUrl = "http://mmanager.codeplex.com/";

        public static string LatestVersion
        {
            get { return _mLatestVersion; }
        }

        public static event Action<string> OnUpdateAvailable;

        public static void CheckUpdates()
        {
            var wf = new WebFetch(WebUrl);
            wf.OnFinished += wf_OnFinished;
            wf.Fetch();
        }

        private static void wf_OnFinished(object sender, FetchEventArgs e)
        {
            const string strReg = "<div class=\"ActivityLabel\">Current</div></td>[\\d\\D]*?<td id=\"ReleaseName\" class=\"ActivityData\">([\\d\\D]*?) ([\\d]*?\\.[\\d]*?)</td>";
            var rRegex = new Regex(strReg, RegexOptions.Multiline);
            var mMatch = rRegex.Match(e.Result);

            if (!mMatch.Success) return;
            var app = mMatch.Groups[1].Value;
            _mLatestVersion = mMatch.Groups[2].Value;

            if (_mLatestVersion != Config.AppVersion && OnUpdateAvailable != null)
            {
                OnUpdateAvailable(_mLatestVersion);
            }
        }
    }
}
